<?php
namespace app\shop\controller;
use app\ApiRest;
use app\integral\info\PermissionIntegral;
use app\integral\model\Integral;
use app\member\model\DiscountGoods;
use app\shop\model\IndexShopOrderGoods;
use app\shop\model\ShareCoupon;
use app\shop\model\ShareCouponId;
use app\Rest;
use app\shop\model\CompanyCoupon;
use app\shop\model\IndexCoupon;
use app\shop\model\IndexUserInfo;
use app\shop\model\UserCoupon;
use think\App;
use think\facade\Db;
use think\Request;
use app\shop\model\IndexCoupon as CouponModel;
use app\shop\model\IndexCouponRecord;
use app\shop\model\IndexGoods;
use app\shop\model\IndexShopSpePrice;



class IndexShopCoupon extends ApiRest
{

    protected $model;
    protected $record_model;
    protected $goods_model;
    protected $spe_price_model;

    public function __construct(App $app) {
        parent::__construct($app);
        $this->model  = new CouponModel();
        $this->record_model = new IndexCouponRecord();
        $this->goods_model  = new IndexGoods();
        $this->spe_price_model = new IndexShopSpePrice();
        $this->model->endCoupon();
        $this->record_model->endRecord();

    }
    /**
     * 员工端福包列表
     */
    public function staffCouponList(){

        $input   = $this->_param;

        $dis[]   = ['uniacid','=',$this->_uniacid];

        $where['uniacid']  = $this->_uniacid;

        $where['staff_id'] = $this->getUserId();

        if(isset($input['send_type'])&&$input['send_type']!=-1){

            $dis[] = ['send_type','=',$input['send_type']];

        }
        $data    = $this->model->staffCouponList($dis,10,$where);

        return $this->success($data);
    }

    /**
     *
     * 用户端优惠券列表
     */

    public function userCouponList(){

        $input   = $this->_param;

        $user_id = $this->getUserId();

        $dis[]   = ['user_id','=',$user_id];

        $dis[]   = ['uniacid','=',$this->_uniacid];

        $dis[]   = ['status' ,'=',$input['status']];

        $data = $this->record_model->recordList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['last_staff_id'] = $this->getUserInfo()['last_staff_id'];
            }

        }

        return $this->success($data);
    }

    /**
     *
     * 员工端福包详情
     */
    public function staffCouponInfo(){

        $input    = $this->_input;

        $staff_id = !empty($input['staff_id'])?$input['staff_id']:$this->getUserId();

        $data['coupon']    = $this->model->couponInfo(['id'=>$input['id']],$staff_id);

        $where['coupon_id']= $input['id'];

        $where['staff_id'] = $this->getUserId();
        //领取数量
        $user_number  = Db::name('longbing_card_coupon_record')->where($where)->count();

        $yu_number    = $data['coupon']['number']-$user_number;

        if($yu_number<=0){

            $data['coupon']['status'] = 2;
        }

        $data['record']    = $this->record_model->recordList(['coupon_id'=>$input['id'],'staff_id'=>$staff_id]);

        $data['my_record'] = $this->record_model->recordInfo(['coupon_id'=>$input['id'],'staff_id'=>$staff_id,'user_id'=>$this->getUserId()]);

        if(!empty($data['record']['data'])){

            foreach ($data['record']['data'] as &$v){

                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }

        }

        return $this->success($data);
    }


    /**
     * 优惠券详情
     */
    public function recordInfo(){

        $input = $this->_input;

        $data  = $this->record_model->recordInfo(['id'=>$input['id']]);

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        if($data['company_limit']==1){

            $company_coupon_model = new CompanyCoupon();

            $dis = [

                'a.coupon_id' => $data['id'],

                'a.type'      => 1
            ];

            $data['company'] = $company_coupon_model->getCompany($dis);

        }
        return $this->success($data);
    }


    /**
     * @return \think\Response
     * 获取可领取的优惠券
     */

    public function CouponListStatus(){

        $input   = $this->_param;

        $user_id = $this->getUserId();

        $to_uid  = $input['staff_id'];

        $coupon_dis['status']  = 1;

        $coupon_dis['uniacid'] = $this->_uniacid;

        if(!empty($input['type'])){

            $coupon_dis['type'] = $input['type'];
        }
        //$coupon_where  = ['user_id'=>$user_id,'uniacid'=>$this->_uniacid,'staff_id'=>$to_uid];
        $data = $this->model->couponListGet($coupon_dis,$user_id,$to_uid);

        return $this->success($data);

    }


    /**
     *
     * 获取可以使用到优惠券
     */
    public function couponCanUse(){

        $discount_goods_model = new DiscountGoods();

        $integral_model       = new Integral();

        $order_goods_model    = new IndexShopOrderGoods();

        $input = $this->_input;

        $is_integral = !empty($input['is_integral'])?1:0;

        $dis[] = ['uniacid' ,'=',$this->_uniacid];

        $dis[] = ['user_id' ,'=',$this->getUserId()];

        $dis[] = ['status'  ,'=',1];

        $dis[] = ['type'    ,'=',1];

        $dis[] = ['end_time','>',time()];

        $where[] = ['staff_id','=',$input['staff_id']];

        $where[] = ['send_type','=',2];

        $coupon = $this->record_model
                    ->where($dis)
                    ->where(function ($query) use ($where){
                    $query->whereOr($where);})
                    ->select()
                    ->toArray();

        $sale_discount = 1;
        //检查积分商城权限
        $i_p = new PermissionIntegral($this->_uniacid);

        $input['buy_limit'] = 1;

        $discount_add = 1;

        if($i_p==true){
            //获取积分商城信息(是否必须用积分，是否可以叠加优惠)
            $integral_data = $integral_model->getBuyLimit($input['goods_info']);

            $discount_add  = (!empty($input['is_integral'])||$integral_data['buy_limit']==0)&&$integral_data['discount_add']==0?0:1;

            $input['buy_limit'] = $integral_data['buy_limit'];

            if($discount_add==0){

                return $this->success([]);
            }

        }

        if(!empty($coupon)){

            foreach ($coupon as &$item){

                $all_price = 0;

                foreach ($input['goods_info'] as &$vs){

                    $goods_where['id'] = $vs['goods_id'];
                    //商品信息
                    $goods = $this->goods_model->goodsInfo($goods_where);

                    $dis = array();

                    if($item['limit_type']==1&&!empty($item['limit_cate'])){

                        $limit_cate = explode(',',$item['limit_cate']);

                        $dis[]      = ['type','in',$limit_cate];

                        $dis[]      = ['id','=',$vs['goods_id']];

                    }elseif($item['limit_type']==2&&!empty($item['limit_goods'])){

                        $limit_goods= explode(',',$item['limit_goods']);

                        $dis[]      = in_array($vs['goods_id'],$limit_goods)?['id','=',$vs['goods_id']]:['id','=','not id'];

                    }else{

                        $dis[]      = ['id','=',$vs['goods_id']];

                    }

                    $is_goods_price = $this->goods_model->where($dis)->find();

                    $goods_price    = 0;

                    if(!empty($is_goods_price)){

                        $is_goods_price = $is_goods_price->toArray();

                        $spe = $this->spe_price_model->SpePriceFind(['id'=>$vs['spe_price_id']]);
                        //固定价格活动 拼团 砍价 积分商城等活动
                        $atv_data = $order_goods_model->payOrderInfoAtv($input,$spe,$is_goods_price);

                        if(empty($atv_data['code'])){

                            $goods       = $atv_data['goods'];

                            $goods_price = $atv_data['spe']['price'];

                        }

                    }
                    //所有关于折扣的信息 会员折扣、批发价折扣
                    $discount_arr = $order_goods_model->orderGoodsDiscount($goods,$this->getUserId(),$this->_uniacid,$vs,$input,$discount_add);

                    if($discount_arr['sale_discount']!=1){

                        $sale_discount = 0;
                    }

                    $discount_member = $discount_goods_model->userGoodsDiscount($vs['goods_id'],$this->getUserId(),$this->_uniacid);

                    $all_price += $goods_price*$vs['number']*$discount_member;
                }

                //优惠券的类型 1是无门槛
                $coupon_type = $item['full']==0?1:0;

                if($sale_discount==1&&($coupon_type==0&&$item['full'] <= $all_price)||($coupon_type==1&&$item['full']<$all_price)){

                    $list[] =  $item;
                }
            }

        }
        $list = !empty($list)?array_values($list):array();

        return $this->success($list);
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-24 14:30
     * @功能说明:积分兑换卡券
     */
    public function integralCouponGet(){

        $input = $this->_input;

        $integral_model = new Integral();

        $member_i_model = new \app\member\model\Integral();
        //活动详情
        $atv = $integral_model->buyLimit($input['id'],$input['id'],2);

        if(empty($atv)){

            $this->errorMsg('活动已经结束');
        }

        $check = $integral_model->getDataCondition($this->getUserId(),$atv,1,4,2);

        if($check!=1){

            $msg = $check==2?'积分不足':'超出兑换限制';

            $this->errorMsg($msg);

        }

        if($atv['have_stock']>=$atv['stock']){

            $this->errorMsg('可兑换数量不足');

        }
        //卡券详情
        $coupon = $this->model->couponInfo(['id'=>$input['id']],$input['staff_id']);

        Db::startTrans();

        $input['user_id'] = $this->getUserId();
        //领取
        $record_id = $this->record_model->insertRecord($coupon,$input);
        //增加积分流水记录
        $res = $member_i_model->integralUserAdd($this->getUserId(),$atv['integral']*-1,$this->_uniacid,1,4,$record_id,$atv['id'],1,0,0,$atv['shop_goods_id']);

        if($res==0){

            Db::rollback();

            $this->errorMsg('兑换人数过多，请稍后再试');

        }
        //扣除积分
        $member_i_model->incUserIntegral($record_id,$this->getUserId(),$this->_uniacid,4);

        Db::commit();

        return $this->success(1);

    }


    /**
     * 领取福包
     */
    public function couponGet(){

        $input   = $this->_input;

        $user_id = $this->getUserId();

        $coupon  = $this->model->couponInfo(['id'=>$input['id']],$input['staff_id']);

        if(empty($coupon)){

            return $this->error('没有发现该福包');
        }
        if ($user_id == $input['staff_id']) {

            return $this->error( '自己不能领取自己的卡券!');
        }
        //领取身份
        if($coupon['get_identity']==1){
            //model
            $user_coupon_model = new UserCoupon();
            //该优惠券哪些用户可以领取
            $can_user = $user_coupon_model->couponUserId(['coupon_id'=>$coupon['id']]);

            if(!in_array($user_id,$can_user)){

                return $this->error( '该优惠券指定用户可领取!');

            }
        }
        //限领次数
        if($coupon['time_limit']==1){
            //领取次数
            $user_count = $this->record_model->where(['coupon_id'=>$coupon['id'],'user_id'=>$user_id])->count();

            if($user_count>=$coupon['get_time']){

                return $this->error( '超过领取次数!');

            }
        }

        $record = $this->record_model->recordInfo(['staff_id' => $input['staff_id'], 'coupon_id' => $input['id'], 'user_id' => $user_id]);

        if(!empty($record)){

            return $this->error( '你已经领取过该福包了!');

        }

        $record_count = $this->record_model->recordCount(['staff_id' => $input['staff_id'], 'coupon_id' => $input['id']]);

        if($coupon['number']<=$record_count){

            return $this->error( '福包已领完!');
        }
        $input['user_id'] = $this->getUserId();
        //领取
        $this->record_model->insertRecord($coupon,$input);

        return $this->success(1);
    }


    /**
     *
     * 核销福包
     */
    public function couponHx(){
        $input = $this->_input;

        $user  = $this->getUserInfo();

        $coupon_pwd          = $input['pwd'];

        $coupon_record_check = $this->record_model->recordInfo(['id' => $input['id']]);

        if($user['is_staff']!=1){

            return $this->error( '只有员工才能核销!');
        }
        if(!empty($coupon_pwd)&&$coupon_pwd!=$this->_config['coupon_pass']){

            return $this->error( '核销密码错误!');
        }

        if (!$coupon_record_check) {
            return $this->error( '未找到该福包领取记录!');
        }

        if ($coupon_record_check['type'] != 2) {
            return $this->error( '只有线下福包才能核销!');
        }

        if ($coupon_record_check['end_time'] < time()) {
            return $this->error( '福包已过期!');
        }

        if ($coupon_record_check['start_time'] >time()) {

            return $this->error( '未到核销时间,核销时间'.date('Y-m-d H:i:s',$coupon_record_check['start_time']));
        }

        if ($coupon_record_check['status'] != 1) {

            return $this->error( '只有待使用的福包才能核销!');
        }

        if($coupon_record_check['company_limit']==1){

            $user_model     = new IndexUserInfo();
            //优惠券公司
            $coupon_company = new CompanyCoupon();
            //该员工的所属公司
            $user_company   = $user_model->getCompanyId(['fans_id'=>$this->getUserId()],$this->_uniacid);

            $dis = [

                'type' => 1,

                'coupon_id' => $coupon_record_check['id']

            ];
            //限用公司
            $limit_company = $coupon_company->where($dis)->column('company_id');

            if(!in_array($user_company,$limit_company)){

                return $this->error( '只有限用公司下面的员工才能核销');

            }
        }

        $res = $this->record_model->recordUpdate(['id' => $input['id']],['status'=>2]);

        return $this->success($res);

    }


    /**
     * User: chenniang
     * Date: 2019-09-18 14:38
     * @return void
     * descption:获取福包二维码
     */
    public function couponQr(){
        $input = $this->_param;
        $record= $this->record_model->recordInfo(['id'=>$input['id'],'user_id'=>$this->getUserId()]);
        if(empty($record)){
            return $this->error('no data');
        }
        if ($record['type']!=2){
            return $this->error('Only offline package can be cancelled');
        }
        if ($record['end_time']<time()){
            return $this->error('The coupon has expired');
        }
        $coupon_qr = getCache($this->getUserId().'-'.$input['id'].'-'.'coupon_qr');
        if(empty($coupon_qr)){
            $data      = longbingCreateWxCode($this->_uniacid,$input,'shop/pages/coupon/hexiao');
            if(isset($data['qr_path'])) $data = transImagesOne($data ,['qr_path'] ,$this->_uniacid);
            $coupon_qr = $data['qr_path'];
            setCache($this->getUserId().'-'.$input['id'].'-'.'coupon_qr',$coupon_qr);
        }
        return $this->success($coupon_qr);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-05-29 14:56
     * @功能说明:优惠券列表
     */
    public function couponInfo(){

        $input = $this->_input;

        $coupon  = $this->model->where(['id'=>$input['id']])->find();

        if(empty($coupon)){

            $this->errorMsg('优惠券未找到');
        }

        $coupon = $coupon->toArray();

        if($coupon['company_limit']==1){

            $company_coupon_model = new CompanyCoupon();

            $dis = [

                'a.coupon_id' => $coupon['id'],

                'a.type'      => 0
            ];

            $coupon['company'] = $company_coupon_model->getCompany($dis);
        }

        $coupon['create_time'] = date('Y-m-d H:i:s',$coupon['create_time']);
        //检查积分商城权限
        $i_p = new PermissionIntegral($this->_uniacid);

        if($i_p==true){

            $i_model = new Integral();

            $i_model->initAtv();
            //正在进行中对活动
            $coupon['integral_atv'] = $i_model->atvIng($coupon['id'],0,2);
            //是否有获取的条件
            $coupon['integral_atv']['can_get'] = $i_model->getDataCondition($this->getUserId(),$coupon['integral_atv'],1);

        }

        return $this->success($coupon);

    }





    /**
     * @author chenniang
     * @DataTime: 2020-09-15 09:32
     * @功能说明:分销优惠券
     */
    public function shareCoupon(){

        $input = $this->_input;

        $inputs['uniacid']  = $this->_uniacid;

        $share_coupon_model = new ShareCoupon();

        Db::startTrans();
        $id = $share_coupon_model->addData($inputs);

        if(!empty($input['coupon'])){

            $share_coupon_id = new ShareCouponId();

            foreach ($input['coupon'] as &$value){

                $value['uniacid']  = $this->_uniacid;

                $value['staff_id'] = $this->getUserId();

                $value['share_id'] = $id;

            }

            $share_coupon_id->saveAll($input['coupon']);

        }else{

            $this->errorMsg('请选择卡券');

        }

        Db::commit();

        return $this->success($id);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-15 09:51
     * @功能说明:分销出来的优惠券详情
     */
    public function shareCouponInfo(){

        $input = $this->_input;

        $share_coupon_id = new ShareCouponId();

        $share_coupon = $share_coupon_id->where(['share_id'=>$input['id']])->select()->toArray();

        $share_coupon_id = array_column($share_coupon,'coupon_id');

        $coupon_model = new IndexCoupon();

        $coupon_dis[] = ['status','=',1];

        $coupon_dis[] = ['uniacid','=',$this->_uniacid];

        $coupon_dis[] = ['id','in',$share_coupon_id];

        $num = 0;

        if($share_coupon[0]['staff_id']!=$this->getUserId()){
            //可以获取的优惠券列表
            $data = $coupon_model->couponListSelect($coupon_dis,$this->getUserId(),$share_coupon[0]['staff_id'],1000,1);

            if(!empty($data)){

                foreach ($data as &$v){

                    foreach ($share_coupon as $value){

                        if($v['id'] == $value['coupon_id']){

                            $v['num'] = $value['num'];

                            $v['staff_id'] = $value['staff_id'];

                        }

                    }
                    $num +=$v['num'];

                    $order = [

                        'user_id' => $this->getUserId(),

                        'staff_id'=> $v['staff_id']
                    ];

                    for ($i=0;$i<$v['num'];$i++){
                        //领取
                        $this->record_model->insertRecord($v,$order);

                    }

                    $v['create_time'] = date('Y.m.d',$v['create_time']);

                    $end_type = $v['end_time_type']==1?$v['end_time_day']*86400+time():0;

                    $v['end_time']   = date('Y.m.d',$v['end_time']+$end_type);

                }

            }
        }else{

            $data = [];
        }

        $arr['data'] = $data;
        //员工信息
        $arr['staff_info'] = [

            'staff_id'  => $share_coupon[0]['staff_id'],

            'staff_name'=> lbUserName($share_coupon[0]['staff_id'])

        ];

        $arr['num'] = $num;

        return $this->success($arr);


    }


















}
